<template>
  <el-dialog
    :model-value="dialogModify"
    width="25%"
    :before-close="handleClose"
  >
    <template #header>
      <h3 style="padding-bottom: 10px">编辑角色</h3>
    </template>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="auto">
      <el-form-item label="用户名称" prop="roleName">
        <el-input
          v-model="form.roleName"
          placeholder="请输入角色名称"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleCode">
        <el-select v-model="form.roleCode" placeholder="请输入权限字符">
          <el-option
            :label="item.roleCode"
            :value="item.id"
            v-for="item in roleList"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单权限" prop="resourceList">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox-group
          v-model="form.resourceList"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox
            v-for="menu in menusList"
            :key="menu.id"
            :label="menu.resourceName"
            :value="menu.id"
          >
            {{ menu.resourceName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" prop="banned">
        <el-radio-group v-model="form.banned">
          <el-radio value="0" size="large">正常</el-radio>
          <el-radio value="1" size="large">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, onUpdated } from 'vue';
import { RoleList } from '@/api/permission/user.js';
import { AddModifyRole, GetmenuList } from '@/api/permission/role';
// 添加用户数据
const form = ref({
  id: '',
  roleName: '',
  roleCode: '',
  banned: '',
  resourceList: [],
});
// 菜单权限多选框数据
const menusList = ref([]);
const checkAll = ref(false);
const isIndeterminate = ref(false);
// 校验规则
const formRef = ref(null);
const rules = {
  roleCode: [{ required: true, message: '请输入权限字符', trigger: 'change' }],
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  banned: [{ required: true, message: '请选择状态', trigger: 'change' }],
  resourceList: [
    { required: true, message: '请至少选择一项选择', trigger: 'change' },
  ],
};
// 下拉列表
const roleList = ref([]);
// 定义 props，接收父组件传递的数据

const props = defineProps({
  dialogModify: {
    type: Boolean,
  },
  NewModifyList: {
    type: Array,
  },
});
// 多选框事件
const handleCheckAllChange = (val) => {
  let newmenusId = menusList.value.map((item) => {
    return item.id;
  });
  form.value.resourceList = val ? newmenusId : [];
  isIndeterminate.value = false;
};
// 单选事件
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === menusList.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < menusList.value.length;
};
// 定义 emits，向父组件发送事件
const emit = defineEmits(['confirm', 'cancel']);

// 定义响应式变量，控制对话框的显示和隐藏

// 处理取消按钮的点击事件
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  emit('cancel');
};

// 处理确认按钮的点击事件
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await AddModifyRole({
        ...form.value,
      });
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'success',
        });
        handleCancel();
        emit('confirm');
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    }
  });
};

// 关闭对话框
const handleClose = () => {
  handleCancel();
};
// 获取角色下拉列表
const getRoleList = async () => {
  const res = await RoleList();
  roleList.value = res.data.data;
};
// 获取菜单列表
const menuList = async () => {
  const res = await GetmenuList();
  menusList.value = res.data.data;
};

onMounted(() => {
  getRoleList();
  menuList();
});
onUpdated(() => {
  form.value.roleName = props.NewModifyList[0].roleName;
  form.value.roleCode = props.NewModifyList[0].roleCode;
  form.value.banned = String(props.NewModifyList[0].banned);
  form.value.resourceList = props.NewModifyList[0].resourceList || [];
  form.value.id = props.NewModifyList[0].id;
  // 使用 map 方法将每个元素转换为字符串
  let stringArray = form.value.resourceList.map(function (number) {
    return number.toString();
  });
  form.value.resourceList = stringArray || [];
  if (form.value.resourceList.length >= 12) {
    checkAll.value = true;
    isIndeterminate.value = false;
  } else if (
    form.value.resourceList.length > 0 &&
    form.value.resourceList.length < 12
  ) {
    isIndeterminate.value = true;
    checkAll.value = false;
  } else {
    checkAll.value = false;
    isIndeterminate.value = false;
  }
});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
